3 * Blocks and bans object
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
42 public $mParentBlockId;
48 protected $mFromMaster;
51 protected $mBlockEmail;
54 protected $mDisableUsertalk;
57 protected $mCreateAccount;
59 /** @var User|string */
62 /** @var int Hack for foreign blocking (CentralAuth) */
63 protected $forcedTargetID;
65 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
72 protected $isHardblock;
75 protected $isAutoblocking;
77 /** @var string|null */
78 protected $systemBlockType;
88 * Create a new block with specified parameters on a user, IP or IP range.
90 * @param array $options Parameters of the block:
91 * address string|User Target user name, User object, IP address or IP range
92 * user int Override target user ID (for foreign users)
93 * by int User ID of the blocker
94 * reason string Reason of the block
95 * timestamp string The time at which the block comes into effect
96 * auto bool Is this an automatic block?
97 * expiry string Timestamp of expiration of the block or 'infinity'
98 * anonOnly bool Only disallow anonymous actions
99 * createAccount bool Disallow creation of new accounts
100 * enableAutoblock bool Enable automatic blocking
101 * hideName bool Hide the target user name
102 * blockEmail bool Disallow sending emails
103 * allowUsertalk bool Allow the target to edit its own talk page
104 * byText string Username of the blocker (for foreign users)
105 * systemBlock string Indicate that this block is automatically
106 * created by MediaWiki rather than being stored
107 * in the database. Value is a string to return
108 * from self::getSystemBlockType().
110 * @since 1.26 accepts $options array instead of individual parameters; order
111 * of parameters above reflects the original order
113 function __construct( $options = [] ) {
123 'createAccount' => false,
124 'enableAutoblock' => false,
126 'blockEmail' => false,
127 'allowUsertalk' => false,
129 'systemBlock' => null,
132 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
133 $options = array_combine(
134 array_slice( array_keys( $defaults ), 0, func_num_args() ),
137 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
140 $options +
= $defaults;
142 $this->setTarget( $options['address'] );
144 if ( $this->target
instanceof User
&& $options['user'] ) {
145 # Needed for foreign users
146 $this->forcedTargetID
= $options['user'];
149 if ( $options['by'] ) {
151 $this->setBlocker( User
::newFromId( $options['by'] ) );
154 $this->setBlocker( $options['byText'] );
157 $this->mReason
= $options['reason'];
158 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
159 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $options['expiry'] );
162 $this->mAuto
= (bool)$options['auto'];
163 $this->mHideName
= (bool)$options['hideName'];
164 $this->isHardblock( !$options['anonOnly'] );
165 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
167 # Prevention measures
168 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
169 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
170 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
172 $this->mFromMaster
= false;
173 $this->systemBlockType
= $options['systemBlock'];
177 * Load a blocked user from their block id.
179 * @param int $id Block id to search for
182 public static function newFromID( $id ) {
183 $dbr = wfGetDB( DB_REPLICA
);
184 $res = $dbr->selectRow(
186 self
::selectFields(),
191 return self
::newFromRow( $res );
198 * Return the list of ipblocks fields that should be selected to create
202 public static function selectFields() {
212 'ipb_create_account',
213 'ipb_enable_autoblock',
217 'ipb_allow_usertalk',
218 'ipb_parent_block_id',
223 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
224 * the blocking user or the block timestamp, only things which affect the blocked user
226 * @param Block $block
230 public function equals( Block
$block ) {
232 (string)$this->target
== (string)$block->target
233 && $this->type
== $block->type
234 && $this->mAuto
== $block->mAuto
235 && $this->isHardblock() == $block->isHardblock()
236 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
237 && $this->mExpiry
== $block->mExpiry
238 && $this->isAutoblocking() == $block->isAutoblocking()
239 && $this->mHideName
== $block->mHideName
240 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
241 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
242 && $this->mReason
== $block->mReason
247 * Load a block from the database which affects the already-set $this->target:
248 * 1) A block directly on the given user or IP
249 * 2) A rangeblock encompassing the given IP (smallest first)
250 * 3) An autoblock on the given IP
251 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
252 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
253 * @throws MWException
254 * @return bool Whether a relevant block was found
256 protected function newLoad( $vagueTarget = null ) {
257 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_REPLICA
);
259 if ( $this->type
!== null ) {
261 'ipb_address' => [ (string)$this->target
],
264 $conds = [ 'ipb_address' => [] ];
267 # Be aware that the != '' check is explicit, since empty values will be
268 # passed by some callers (bug 29116)
269 if ( $vagueTarget != '' ) {
270 list( $target, $type ) = self
::parseTarget( $vagueTarget );
272 case self
::TYPE_USER
:
273 # Slightly weird, but who are we to argue?
274 $conds['ipb_address'][] = (string)$target;
278 $conds['ipb_address'][] = (string)$target;
279 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
280 $conds = $db->makeList( $conds, LIST_OR
);
283 case self
::TYPE_RANGE
:
284 list( $start, $end ) = IP
::parseRange( $target );
285 $conds['ipb_address'][] = (string)$target;
286 $conds[] = self
::getRangeCond( $start, $end );
287 $conds = $db->makeList( $conds, LIST_OR
);
291 throw new MWException( "Tried to load block with invalid type" );
295 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
297 # This result could contain a block on the user, a block on the IP, and a russian-doll
298 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
301 # Lower will be better
302 $bestBlockScore = 100;
304 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
305 $bestBlockPreventsEdit = null;
307 foreach ( $res as $row ) {
308 $block = self
::newFromRow( $row );
310 # Don't use expired blocks
311 if ( $block->isExpired() ) {
315 # Don't use anon only blocks on users
316 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
320 if ( $block->getType() == self
::TYPE_RANGE
) {
321 # This is the number of bits that are allowed to vary in the block, give
322 # or take some floating point errors
323 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
324 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
325 $size = log( $end - $start +
1, 2 );
327 # This has the nice property that a /32 block is ranked equally with a
328 # single-IP block, which is exactly what it is...
329 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
332 $score = $block->getType();
335 if ( $score < $bestBlockScore ) {
336 $bestBlockScore = $score;
338 $bestBlockPreventsEdit = $block->prevents( 'edit' );
342 if ( $bestRow !== null ) {
343 $this->initFromRow( $bestRow );
344 $this->prevents( 'edit', $bestBlockPreventsEdit );
352 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
353 * @param string $start Hexadecimal IP representation
354 * @param string $end Hexadecimal IP representation, or null to use $start = $end
357 public static function getRangeCond( $start, $end = null ) {
358 if ( $end === null ) {
361 # Per bug 14634, we want to include relevant active rangeblocks; for
362 # rangeblocks, we want to include larger ranges which enclose the given
363 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
364 # so we can improve performance by filtering on a LIKE clause
365 $chunk = self
::getIpFragment( $start );
366 $dbr = wfGetDB( DB_REPLICA
);
367 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
369 # Fairly hard to make a malicious SQL statement out of hex characters,
370 # but stranger things have happened...
371 $safeStart = $dbr->addQuotes( $start );
372 $safeEnd = $dbr->addQuotes( $end );
374 return $dbr->makeList(
376 "ipb_range_start $like",
377 "ipb_range_start <= $safeStart",
378 "ipb_range_end >= $safeEnd",
385 * Get the component of an IP address which is certain to be the same between an IP
386 * address and a rangeblock containing that IP address.
387 * @param string $hex Hexadecimal IP representation
390 protected static function getIpFragment( $hex ) {
391 global $wgBlockCIDRLimit;
392 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
393 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
395 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
400 * Given a database row from the ipblocks table, initialize
402 * @param stdClass $row A row from the ipblocks table
404 protected function initFromRow( $row ) {
405 $this->setTarget( $row->ipb_address
);
406 if ( $row->ipb_by
) { // local user
407 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
408 } else { // foreign user
409 $this->setBlocker( $row->ipb_by_text
);
412 $this->mReason
= $row->ipb_reason
;
413 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
414 $this->mAuto
= $row->ipb_auto
;
415 $this->mHideName
= $row->ipb_deleted
;
416 $this->mId
= (int)$row->ipb_id
;
417 $this->mParentBlockId
= $row->ipb_parent_block_id
;
419 // I wish I didn't have to do this
420 $this->mExpiry
= wfGetDB( DB_REPLICA
)->decodeExpiry( $row->ipb_expiry
);
422 $this->isHardblock( !$row->ipb_anon_only
);
423 $this->isAutoblocking( $row->ipb_enable_autoblock
);
425 $this->prevents( 'createaccount', $row->ipb_create_account
);
426 $this->prevents( 'sendemail', $row->ipb_block_email
);
427 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
431 * Create a new Block object from a database row
432 * @param stdClass $row Row from the ipblocks table
435 public static function newFromRow( $row ) {
437 $block->initFromRow( $row );
442 * Delete the row from the IP blocks table.
444 * @throws MWException
447 public function delete() {
448 if ( wfReadOnly() ) {
452 if ( !$this->getId() ) {
453 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
456 $dbw = wfGetDB( DB_MASTER
);
457 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__
);
458 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__
);
460 return $dbw->affectedRows() > 0;
464 * Insert a block into the block table. Will fail if there is a conflicting
465 * block (same name and options) already in the database.
467 * @param IDatabase $dbw If you have one available
468 * @return bool|array False on failure, assoc array on success:
469 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
471 public function insert( $dbw = null ) {
472 global $wgBlockDisablesLogin;
474 if ( $this->getSystemBlockType() !== null ) {
475 throw new MWException( 'Cannot insert a system block into the database' );
478 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
480 if ( $dbw === null ) {
481 $dbw = wfGetDB( DB_MASTER
);
484 # Periodic purge via commit hooks
485 if ( mt_rand( 0, 9 ) == 0 ) {
486 Block
::purgeExpired();
489 $row = $this->getDatabaseArray();
490 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
492 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
493 $affected = $dbw->affectedRows();
494 $this->mId
= $dbw->insertId();
496 # Don't collide with expired blocks.
497 # Do this after trying to insert to avoid locking.
499 # T96428: The ipb_address index uses a prefix on a field, so
500 # use a standard SELECT + DELETE to avoid annoying gap locks.
501 $ids = $dbw->selectFieldValues( 'ipblocks',
504 'ipb_address' => $row['ipb_address'],
505 'ipb_user' => $row['ipb_user'],
506 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
511 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__
);
512 $dbw->insert( 'ipblocks', $row, __METHOD__
, [ 'IGNORE' ] );
513 $affected = $dbw->affectedRows();
514 $this->mId
= $dbw->insertId();
519 $auto_ipd_ids = $this->doRetroactiveAutoblock();
521 if ( $wgBlockDisablesLogin && $this->target
instanceof User
) {
522 // Change user login token to force them to be logged out.
523 $this->target
->setToken();
524 $this->target
->saveSettings();
527 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
534 * Update a block in the DB with new parameters.
535 * The ID field needs to be loaded first.
537 * @return bool|array False on failure, array on success:
538 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
540 public function update() {
541 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
542 $dbw = wfGetDB( DB_MASTER
);
544 $dbw->startAtomic( __METHOD__
);
548 $this->getDatabaseArray( $dbw ),
549 [ 'ipb_id' => $this->getId() ],
553 $affected = $dbw->affectedRows();
555 if ( $this->isAutoblocking() ) {
556 // update corresponding autoblock(s) (bug 48813)
559 $this->getAutoblockUpdateArray(),
560 [ 'ipb_parent_block_id' => $this->getId() ],
564 // autoblock no longer required, delete corresponding autoblock(s)
567 [ 'ipb_parent_block_id' => $this->getId() ],
572 $dbw->endAtomic( __METHOD__
);
575 $auto_ipd_ids = $this->doRetroactiveAutoblock();
576 return [ 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids ];
583 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
584 * @param IDatabase $db
587 protected function getDatabaseArray( $db = null ) {
589 $db = wfGetDB( DB_REPLICA
);
591 $expiry = $db->encodeExpiry( $this->mExpiry
);
593 if ( $this->forcedTargetID
) {
594 $uid = $this->forcedTargetID
;
596 $uid = $this->target
instanceof User ?
$this->target
->getId() : 0;
600 'ipb_address' => (string)$this->target
,
602 'ipb_by' => $this->getBy(),
603 'ipb_by_text' => $this->getByName(),
604 'ipb_reason' => $this->mReason
,
605 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
606 'ipb_auto' => $this->mAuto
,
607 'ipb_anon_only' => !$this->isHardblock(),
608 'ipb_create_account' => $this->prevents( 'createaccount' ),
609 'ipb_enable_autoblock' => $this->isAutoblocking(),
610 'ipb_expiry' => $expiry,
611 'ipb_range_start' => $this->getRangeStart(),
612 'ipb_range_end' => $this->getRangeEnd(),
613 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
614 'ipb_block_email' => $this->prevents( 'sendemail' ),
615 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
616 'ipb_parent_block_id' => $this->mParentBlockId
625 protected function getAutoblockUpdateArray() {
627 'ipb_by' => $this->getBy(),
628 'ipb_by_text' => $this->getByName(),
629 'ipb_reason' => $this->mReason
,
630 'ipb_create_account' => $this->prevents( 'createaccount' ),
631 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
632 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
637 * Retroactively autoblocks the last IP used by the user (if it is a user)
638 * blocked by this Block.
640 * @return array Block IDs of retroactive autoblocks made
642 protected function doRetroactiveAutoblock() {
644 # If autoblock is enabled, autoblock the LAST IP(s) used
645 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
646 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
648 $continue = Hooks
::run(
649 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
652 self
::defaultRetroactiveAutoblock( $this, $blockIds );
659 * Retroactively autoblocks the last IP used by the user (if it is a user)
660 * blocked by this Block. This will use the recentchanges table.
662 * @param Block $block
663 * @param array &$blockIds
665 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
668 // No IPs are in recentchanges table, so nothing to select
669 if ( !$wgPutIPinRC ) {
673 $dbr = wfGetDB( DB_REPLICA
);
675 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
676 $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
678 // Just the last IP used.
679 $options['LIMIT'] = 1;
681 $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
682 __METHOD__
, $options );
684 if ( !$res->numRows() ) {
685 # No results, don't autoblock anything
686 wfDebug( "No IP found to retroactively autoblock\n" );
688 foreach ( $res as $row ) {
690 $id = $block->doAutoblock( $row->rc_ip
);
700 * Checks whether a given IP is on the autoblock whitelist.
701 * TODO: this probably belongs somewhere else, but not sure where...
703 * @param string $ip The IP to check
706 public static function isWhitelistedFromAutoblocks( $ip ) {
707 // Try to get the autoblock_whitelist from the cache, as it's faster
708 // than getting the msg raw and explode()'ing it.
709 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
710 $lines = $cache->getWithSetCallback(
711 wfMemcKey( 'ipb', 'autoblock', 'whitelist' ),
713 function ( $curValue, &$ttl, array &$setOpts ) {
714 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
716 return explode( "\n",
717 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
721 wfDebug( "Checking the autoblock whitelist..\n" );
723 foreach ( $lines as $line ) {
725 if ( substr( $line, 0, 1 ) !== '*' ) {
729 $wlEntry = substr( $line, 1 );
730 $wlEntry = trim( $wlEntry );
732 wfDebug( "Checking $ip against $wlEntry..." );
734 # Is the IP in this range?
735 if ( IP
::isInRange( $ip, $wlEntry ) ) {
736 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
739 wfDebug( " No match\n" );
747 * Autoblocks the given IP, referring to this Block.
749 * @param string $autoblockIP The IP to autoblock.
750 * @return int|bool Block ID if an autoblock was inserted, false if not.
752 public function doAutoblock( $autoblockIP ) {
753 # If autoblocks are disabled, go away.
754 if ( !$this->isAutoblocking() ) {
758 # Don't autoblock for system blocks
759 if ( $this->getSystemBlockType() !== null ) {
760 throw new MWException( 'Cannot autoblock from a system block' );
763 # Check for presence on the autoblock whitelist.
764 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
768 # Allow hooks to cancel the autoblock.
769 if ( !Hooks
::run( 'AbortAutoblock', [ $autoblockIP, &$this ] ) ) {
770 wfDebug( "Autoblock aborted by hook.\n" );
774 # It's okay to autoblock. Go ahead and insert/update the block...
776 # Do not add a *new* block if the IP is already blocked.
777 $ipblock = Block
::newFromTarget( $autoblockIP );
779 # Check if the block is an autoblock and would exceed the user block
780 # if renewed. If so, do nothing, otherwise prolong the block time...
781 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
782 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
784 # Reset block timestamp to now and its expiry to
785 # $wgAutoblockExpiry in the future
786 $ipblock->updateTimestamp();
791 # Make a new block object with the desired properties.
792 $autoblock = new Block
;
793 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
794 $autoblock->setTarget( $autoblockIP );
795 $autoblock->setBlocker( $this->getBlocker() );
796 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
797 ->inContentLanguage()->plain();
798 $timestamp = wfTimestampNow();
799 $autoblock->mTimestamp
= $timestamp;
800 $autoblock->mAuto
= 1;
801 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
802 # Continue suppressing the name if needed
803 $autoblock->mHideName
= $this->mHideName
;
804 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
805 $autoblock->mParentBlockId
= $this->mId
;
807 if ( $this->mExpiry
== 'infinity' ) {
808 # Original block was indefinite, start an autoblock now
809 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
811 # If the user is already blocked with an expiry date, we don't
812 # want to pile on top of that.
813 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
816 # Insert the block...
817 $status = $autoblock->insert();
824 * Check if a block has expired. Delete it if it is.
827 public function deleteIfExpired() {
829 if ( $this->isExpired() ) {
830 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
834 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
842 * Has the block expired?
845 public function isExpired() {
846 $timestamp = wfTimestampNow();
847 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
849 if ( !$this->mExpiry
) {
852 return $timestamp > $this->mExpiry
;
857 * Is the block address valid (i.e. not a null string?)
860 public function isValid() {
861 return $this->getTarget() != null;
865 * Update the timestamp on autoblocks.
867 public function updateTimestamp() {
868 if ( $this->mAuto
) {
869 $this->mTimestamp
= wfTimestamp();
870 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
872 $dbw = wfGetDB( DB_MASTER
);
873 $dbw->update( 'ipblocks',
875 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
876 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
879 'ipb_id' => $this->getId(),
887 * Get the IP address at the start of the range in Hex form
888 * @throws MWException
889 * @return string IP in Hex form
891 public function getRangeStart() {
892 switch ( $this->type
) {
893 case self
::TYPE_USER
:
896 return IP
::toHex( $this->target
);
897 case self
::TYPE_RANGE
:
898 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
901 throw new MWException( "Block with invalid type" );
906 * Get the IP address at the end of the range in Hex form
907 * @throws MWException
908 * @return string IP in Hex form
910 public function getRangeEnd() {
911 switch ( $this->type
) {
912 case self
::TYPE_USER
:
915 return IP
::toHex( $this->target
);
916 case self
::TYPE_RANGE
:
917 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
920 throw new MWException( "Block with invalid type" );
925 * Get the user id of the blocking sysop
927 * @return int (0 for foreign users)
929 public function getBy() {
930 $blocker = $this->getBlocker();
931 return ( $blocker instanceof User
)
937 * Get the username of the blocking sysop
941 public function getByName() {
942 $blocker = $this->getBlocker();
943 return ( $blocker instanceof User
)
944 ?
$blocker->getName()
945 : (string)$blocker; // username
952 public function getId() {
957 * Get the system block type, if any
958 * @return string|null
960 public function getSystemBlockType() {
961 return $this->systemBlockType
;
965 * Get/set a flag determining whether the master is used for reads
967 * @param bool|null $x
970 public function fromMaster( $x = null ) {
971 return wfSetVar( $this->mFromMaster
, $x );
975 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
976 * @param bool|null $x
979 public function isHardblock( $x = null ) {
980 wfSetVar( $this->isHardblock
, $x );
982 # You can't *not* hardblock a user
983 return $this->getType() == self
::TYPE_USER
985 : $this->isHardblock
;
989 * @param null|bool $x
992 public function isAutoblocking( $x = null ) {
993 wfSetVar( $this->isAutoblocking
, $x );
995 # You can't put an autoblock on an IP or range as we don't have any history to
996 # look over to get more IPs from
997 return $this->getType() == self
::TYPE_USER
998 ?
$this->isAutoblocking
1003 * Get/set whether the Block prevents a given action
1005 * @param string $action Action to check
1006 * @param bool|null $x Value for set, or null to just get value
1007 * @return bool|null Null for unrecognized rights.
1009 public function prevents( $action, $x = null ) {
1010 global $wgBlockDisablesLogin;
1012 switch ( $action ) {
1014 # For now... <evil laugh>
1017 case 'createaccount':
1018 $res = wfSetVar( $this->mCreateAccount
, $x );
1021 $res = wfSetVar( $this->mBlockEmail
, $x );
1023 case 'editownusertalk':
1024 $res = wfSetVar( $this->mDisableUsertalk
, $x );
1030 if ( !$res && $wgBlockDisablesLogin ) {
1031 // If a block would disable login, then it should
1032 // prevent any action that all users cannot do
1034 $res = $anon->isAllowed( $action ) ?
$res : true;
1041 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1042 * @return string Text is escaped
1044 public function getRedactedName() {
1045 if ( $this->mAuto
) {
1046 return Html
::rawElement(
1048 [ 'class' => 'mw-autoblockid' ],
1049 wfMessage( 'autoblockid', $this->mId
)
1052 return htmlspecialchars( $this->getTarget() );
1057 * Get a timestamp of the expiry for autoblocks
1059 * @param string|int $timestamp
1062 public static function getAutoblockExpiry( $timestamp ) {
1063 global $wgAutoblockExpiry;
1065 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1069 * Purge expired blocks from the ipblocks table
1071 public static function purgeExpired() {
1072 if ( wfReadOnly() ) {
1076 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
1077 wfGetDB( DB_MASTER
),
1079 function ( IDatabase
$dbw, $fname ) {
1082 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1090 * Given a target and the target's type, get an existing Block object if possible.
1091 * @param string|User|int $specificTarget A block target, which may be one of several types:
1092 * * A user to block, in which case $target will be a User
1093 * * An IP to block, in which case $target will be a User generated by using
1094 * User::newFromName( $ip, false ) to turn off name validation
1095 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1096 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1098 * Calling this with a user, IP address or range will not select autoblocks, and will
1099 * only select a block where the targets match exactly (so looking for blocks on
1100 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1101 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1102 * affects that target (so for an IP address, get ranges containing that IP; and also
1103 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1104 * @param bool $fromMaster Whether to use the DB_MASTER database
1105 * @return Block|null (null if no relevant block could be found). The target and type
1106 * of the returned Block will refer to the actual block which was found, which might
1107 * not be the same as the target you gave if you used $vagueTarget!
1109 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1111 list( $target, $type ) = self
::parseTarget( $specificTarget );
1112 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1113 return Block
::newFromID( $target );
1115 } elseif ( $target === null && $vagueTarget == '' ) {
1116 # We're not going to find anything useful here
1117 # Be aware that the == '' check is explicit, since empty values will be
1118 # passed by some callers (bug 29116)
1121 } elseif ( in_array(
1123 [ Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ] )
1125 $block = new Block();
1126 $block->fromMaster( $fromMaster );
1128 if ( $type !== null ) {
1129 $block->setTarget( $target );
1132 if ( $block->newLoad( $vagueTarget ) ) {
1140 * Get all blocks that match any IP from an array of IP addresses
1142 * @param array $ipChain List of IPs (strings), usually retrieved from the
1143 * X-Forwarded-For header of the request
1144 * @param bool $isAnon Exclude anonymous-only blocks if false
1145 * @param bool $fromMaster Whether to query the master or replica DB
1146 * @return array Array of Blocks
1149 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1150 if ( !count( $ipChain ) ) {
1155 $proxyLookup = MediaWikiServices
::getInstance()->getProxyLookup();
1156 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1157 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1158 # necessarily trust the header given to us, make sure that we are only
1159 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1160 # Do not treat private IP spaces as special as it may be desirable for wikis
1161 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1162 if ( !IP
::isValid( $ipaddr ) ) {
1165 # Don't check trusted IPs (includes local squids which will be in every request)
1166 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1169 # Check both the original IP (to check against single blocks), as well as build
1170 # the clause to check for rangeblocks for the given IP.
1171 $conds['ipb_address'][] = $ipaddr;
1172 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1175 if ( !count( $conds ) ) {
1179 if ( $fromMaster ) {
1180 $db = wfGetDB( DB_MASTER
);
1182 $db = wfGetDB( DB_REPLICA
);
1184 $conds = $db->makeList( $conds, LIST_OR
);
1186 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1188 $selectFields = array_merge(
1189 [ 'ipb_range_start', 'ipb_range_end' ],
1190 Block
::selectFields()
1192 $rows = $db->select( 'ipblocks',
1199 foreach ( $rows as $row ) {
1200 $block = self
::newFromRow( $row );
1201 if ( !$block->isExpired() ) {
1210 * From a list of multiple blocks, find the most exact and strongest Block.
1212 * The logic for finding the "best" block is:
1213 * - Blocks that match the block's target IP are preferred over ones in a range
1214 * - Hardblocks are chosen over softblocks that prevent account creation
1215 * - Softblocks that prevent account creation are chosen over other softblocks
1216 * - Other softblocks are chosen over autoblocks
1217 * - If there are multiple exact or range blocks at the same level, the one chosen
1219 * This should be used when $blocks where retrieved from the user's IP address
1220 * and $ipChain is populated from the same IP address information.
1222 * @param array $blocks Array of Block objects
1223 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1224 * a block is to the server, and if a block matches exactly, or is in a range.
1225 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1227 * @throws MWException
1228 * @return Block|null The "best" block from the list
1230 public static function chooseBlock( array $blocks, array $ipChain ) {
1231 if ( !count( $blocks ) ) {
1233 } elseif ( count( $blocks ) == 1 ) {
1237 // Sort hard blocks before soft ones and secondarily sort blocks
1238 // that disable account creation before those that don't.
1239 usort( $blocks, function ( Block
$a, Block
$b ) {
1240 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1241 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1242 return strcmp( $bWeight, $aWeight ); // highest weight first
1245 $blocksListExact = [
1247 'disable_create' => false,
1251 $blocksListRange = [
1253 'disable_create' => false,
1257 $ipChain = array_reverse( $ipChain );
1259 /** @var Block $block */
1260 foreach ( $blocks as $block ) {
1261 // Stop searching if we have already have a "better" block. This
1262 // is why the order of the blocks matters
1263 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1265 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1269 foreach ( $ipChain as $checkip ) {
1270 $checkipHex = IP
::toHex( $checkip );
1271 if ( (string)$block->getTarget() === $checkip ) {
1272 if ( $block->isHardblock() ) {
1273 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1274 } elseif ( $block->prevents( 'createaccount' ) ) {
1275 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1276 } elseif ( $block->mAuto
) {
1277 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1279 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1281 // We found closest exact match in the ip list, so go to the next Block
1283 } elseif ( array_filter( $blocksListExact ) == []
1284 && $block->getRangeStart() <= $checkipHex
1285 && $block->getRangeEnd() >= $checkipHex
1287 if ( $block->isHardblock() ) {
1288 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1289 } elseif ( $block->prevents( 'createaccount' ) ) {
1290 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1291 } elseif ( $block->mAuto
) {
1292 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1294 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1301 if ( array_filter( $blocksListExact ) == [] ) {
1302 $blocksList = &$blocksListRange;
1304 $blocksList = &$blocksListExact;
1307 $chosenBlock = null;
1308 if ( $blocksList['hard'] ) {
1309 $chosenBlock = $blocksList['hard'];
1310 } elseif ( $blocksList['disable_create'] ) {
1311 $chosenBlock = $blocksList['disable_create'];
1312 } elseif ( $blocksList['other'] ) {
1313 $chosenBlock = $blocksList['other'];
1314 } elseif ( $blocksList['auto'] ) {
1315 $chosenBlock = $blocksList['auto'];
1317 throw new MWException( "Proxy block found, but couldn't be classified." );
1320 return $chosenBlock;
1324 * From an existing Block, get the target and the type of target.
1325 * Note that, except for null, it is always safe to treat the target
1326 * as a string; for User objects this will return User::__toString()
1327 * which in turn gives User::getName().
1329 * @param string|int|User|null $target
1330 * @return array( User|String|null, Block::TYPE_ constant|null )
1332 public static function parseTarget( $target ) {
1333 # We may have been through this before
1334 if ( $target instanceof User
) {
1335 if ( IP
::isValid( $target->getName() ) ) {
1336 return [ $target, self
::TYPE_IP
];
1338 return [ $target, self
::TYPE_USER
];
1340 } elseif ( $target === null ) {
1341 return [ null, null ];
1344 $target = trim( $target );
1346 if ( IP
::isValid( $target ) ) {
1347 # We can still create a User if it's an IP address, but we need to turn
1348 # off validation checking (which would exclude IP addresses)
1350 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1354 } elseif ( IP
::isValidBlock( $target ) ) {
1355 # Can't create a User from an IP range
1356 return [ IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
];
1359 # Consider the possibility that this is not a username at all
1360 # but actually an old subpage (bug #29797)
1361 if ( strpos( $target, '/' ) !== false ) {
1362 # An old subpage, drill down to the user behind it
1363 $target = explode( '/', $target )[0];
1366 $userObj = User
::newFromName( $target );
1367 if ( $userObj instanceof User
) {
1368 # Note that since numbers are valid usernames, a $target of "12345" will be
1369 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1370 # since hash characters are not valid in usernames or titles generally.
1371 return [ $userObj, Block
::TYPE_USER
];
1373 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1374 # Autoblock reference in the form "#12345"
1375 return [ substr( $target, 1 ), Block
::TYPE_AUTO
];
1379 return [ null, null ];
1384 * Get the type of target for this particular block
1385 * @return int Block::TYPE_ constant, will never be TYPE_ID
1387 public function getType() {
1394 * Get the target and target type for this particular Block. Note that for autoblocks,
1395 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1396 * in this situation.
1397 * @return array( User|String, Block::TYPE_ constant )
1398 * @todo FIXME: This should be an integral part of the Block member variables
1400 public function getTargetAndType() {
1401 return [ $this->getTarget(), $this->getType() ];
1405 * Get the target for this particular Block. Note that for autoblocks,
1406 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1407 * in this situation.
1408 * @return User|string
1410 public function getTarget() {
1411 return $this->target
;
1417 * @return mixed|string
1419 public function getExpiry() {
1420 return $this->mExpiry
;
1424 * Set the target for this block, and update $this->type accordingly
1425 * @param mixed $target
1427 public function setTarget( $target ) {
1428 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1432 * Get the user who implemented this block
1433 * @return User|string Local User object or string for a foreign user
1435 public function getBlocker() {
1436 return $this->blocker
;
1440 * Set the user who implemented (or will implement) this block
1441 * @param User|string $user Local User object or username string for foreign users
1443 public function setBlocker( $user ) {
1444 $this->blocker
= $user;
1448 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1449 * the same as the block's, to a maximum of 24 hours.
1451 * An empty value can also be set, in order to retain the cookie but remove the block ID
1452 * (e.g. as used in User::getBlockedStatus).
1454 * @param WebResponse $response The response on which to set the cookie.
1455 * @param boolean $setEmpty Whether to set the cookie's value to the empty string.
1457 public function setCookie( WebResponse
$response, $setEmpty = false ) {
1458 // Calculate the default expiry time.
1459 $maxExpiryTime = wfTimestamp( TS_MW
, wfTimestamp() +
( 24 * 60 * 60 ) );
1461 // Use the Block's expiry time only if it's less than the default.
1462 $expiryTime = $this->getExpiry();
1463 if ( $expiryTime === 'infinity' ||
$expiryTime > $maxExpiryTime ) {
1464 $expiryTime = $maxExpiryTime;
1467 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1468 $cookieValue = $setEmpty ?
'' : $this->getId();
1469 $expiryValue = DateTime
::createFromFormat( "YmdHis", $expiryTime );
1470 $response->setCookie( 'BlockID', $cookieValue, $expiryValue->format( "U" ) );
1474 * Get the key and parameters for the corresponding error message.
1477 * @param IContextSource $context
1480 public function getPermissionsError( IContextSource
$context ) {
1481 $blocker = $this->getBlocker();
1482 if ( $blocker instanceof User
) { // local user
1483 $blockerUserpage = $blocker->getUserPage();
1484 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1485 } else { // foreign user
1489 $reason = $this->mReason
;
1490 if ( $reason == '' ) {
1491 $reason = $context->msg( 'blockednoreason' )->text();
1494 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1495 * This could be a username, an IP range, or a single IP. */
1496 $intended = $this->getTarget();
1498 $systemBlockType = $this->getSystemBlockType();
1500 $lang = $context->getLanguage();
1502 $systemBlockType !== null
1503 ?
'systemblockedtext'
1504 : ( $this->mAuto ?
'autoblockedtext' : 'blockedtext' ),
1507 $context->getRequest()->getIP(),
1509 $systemBlockType !== null ?
$systemBlockType : $this->getId(),
1510 $lang->formatExpiry( $this->mExpiry
),
1512 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),